import { useVueFlow, Position } from "@vue-flow/core";
import { ref } from "vue";

export default function useDragAndDrop() {
  const { project } = useVueFlow();
  const isDragging = ref(false);
  const isDragOver = ref(false);

  // 处理拖拽开始
  const onDragStart = (event: DragEvent, processData: any) => {
    if (event.dataTransfer) {
      event.dataTransfer.setData("application/processNode", JSON.stringify(processData));
      event.dataTransfer.effectAllowed = "move";

      // 设置拖拽图像
      const dragEl = event.target as HTMLElement;
      if (dragEl) {
        event.dataTransfer.setDragImage(dragEl, dragEl.offsetWidth / 2, dragEl.offsetHeight / 2);
      }
    }
    isDragging.value = true;
  };

  // 处理拖拽结束
  const onDragEnd = () => {
    isDragging.value = false;
    isDragOver.value = false;
  };

  // 处理拖拽悬停
  const onDragOver = (event: DragEvent) => {
    event.preventDefault();
    if (event.dataTransfer) {
      event.dataTransfer.dropEffect = "move";
    }
    isDragOver.value = true;
  };

  // 处理拖拽离开
  const onDragLeave = () => {
    isDragOver.value = false;
  };

  // 处理节点放置
  const onDrop = (event: DragEvent, reactFlowWrapper: HTMLElement) => {
    event.preventDefault();
    const processData = JSON.parse(event.dataTransfer?.getData("application/processNode") || "{}");

    // 获取画布容器的位置信息
    const reactFlowBounds = reactFlowWrapper.getBoundingClientRect();

    // 计算相对于画布的位置
    const position = project({
      x: event.clientX - reactFlowBounds.left,
      y: event.clientY - reactFlowBounds.top
    });

    // 创建新节点
    const newNode = {
      id: processData.nodeId,
      type: "custom",
      position: {
        x: position.x - 100, // 节点宽度的一半
        y: position.y - 25 // 节点高度的一半
      },
      sourcePosition: Position.Bottom,
      targetPosition: Position.Top,
      data: {
        ...processData,
        label: processData.process.processName,
        nodeId: processData.nodeId
      }
    };

    return newNode;
  };

  return {
    isDragging,
    isDragOver,
    onDragStart,
    onDragEnd,
    onDragOver,
    onDragLeave,
    onDrop
  };
}
